package com.wdz.service.impl;

import com.wdz.redis.RedisUtil;
import com.wdz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

@Service("UserServiceImpl")
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 校验用户是否可以登录 true:可以登录 false：不可以登录,如果可以登录就将信息写入redis
     * @param user
     * @param ip
     * @return
     */
    @Override
    public boolean checkIsLogin(String user, String ip) {
        //线程安全的list
        List<Map<String,Object>> users = new Vector<>();
        final boolean[] boo = {true,true};
        if(redisUtil.get("users") != null){
            users = (List<Map<String, Object>>) redisUtil.get("users");
            //线程安全的迭代list
            users.forEach(item -> {
                assert item.get("user") != null;
                if(item.get("user").equals(user)){
                    long currentTime=System.currentTimeMillis();
                    long createDate = (long) item.get("createDate");
                    if(currentTime - createDate <= 1000*60*60*2) {
                        if (!item.get("ip").equals(ip)) {
                            boo[1] = false;
                        }
                    }else{
                        item.put("ip",ip);
                        item.put("createDate",createDate);
                    }
                    boo[0] = false;
                }
            });
        }
        if(boo[0]) {
            Map<String, Object> user1 = new HashMap<>();
            user1.put("user", user == null?"未知用户":user);
            user1.put("ip", ip);
            //获取当前时间戳
            long currentTime=System.currentTimeMillis();
            user1.put("createDate",currentTime);
            users.add(user1);
            redisUtil.set("users", users);
        }
        return boo[1];
    }

    @Override
    public void deleteUserToRedis(String user) {
        //线程安全的list
        List<Map<String,Object>> users;
        if(redisUtil.get("users") != null){
            users = (List<Map<String, Object>>) redisUtil.get("users");
            //线程安全的迭代list
            List<Map<String, Object>> finalUsers = users;
            users.forEach(item -> {
                if(item.get("user").equals(user)){
                    finalUsers.remove(item);
                }
            });
            users = finalUsers;
            redisUtil.set("users", users);
        }
    }
}
